#setLanguageLevel 4;

//Script: Order to Visma Net - version 03-01-2025 13:00 by SuperOffice InfoBridge

//--Configuration start
//This is the only part of the script where configuration per tenant is needed.
//In variables and other code we use Contact for company (UI and documentation) 
//and we use Person for a contact (UI and documentation). 

//The user friendly name of the ERP system.
String erpPlatform = "Visma Net";

//You can find the INSTANT job URL in the Process step of the DataBridge Integration. (Note: make sure to take the INSTANT job URL).
String instantJobUrl = "";

//The user defined field that indicates if a company card is linked to a company card in ERP. Fill in the Prog ID.
//A bool will be checked for 0/1; a text or number will be checked whether the field is empty.
String fieldContactIsLinkedToERP = "COMPANYLINKEDTOERP";

//The user defined field that indicates if a contact card is linked to a contact card in ERP. Fill in the Prog ID.
//A bool will be checked for 0/1; a text or number will be checked whether the field is empty.
String fieldPersonIsLinkedToERP = "CONTACTLINKEDTOERP";

//The user defined field that indicates if a sale card is linked to a sale card in ERP. Fill in the Prog ID.
//A bool will be checked for 0/1; a text or number will be checked whether the field is empty.
String fieldSaleIsLinkedToERP = "SALEERPORDERNUMBER";

//Do you want to only allow sales with a status 'Sold' to be created in ERP?
Bool allowOnlySaleWithStatusSold = true;

//--Configuration end


EventData ed = getEventData();

String contactId = ed.getInputValue("SaleEntity.Contact.ContactId");
String contactName = ed.getInputValue("SaleEntity.Contact.FullName");
String contactIsLinkedToERP_Value = "";
Bool contactIsLinkedToERP = false;

String personId = ed.getInputValue("SaleEntity.Person.PersonId");
String personName = ed.getInputValue("SaleEntity.Person.FullName");
String personIsLinkedToERP_Value = "";
Bool personIsLinkedToERP = false;

String saleId = ed.getInputValue("SaleEntity.SaleId");
String saleName = ed.getInputValue("SaleEntity.Heading");
String saleStatus = ed.getInputValue("SaleStatus");
Integer quoteId = 0; 
Integer quoteVersionState = 0;
String saleIsLinkedToERP_Value = ed.getInputValue("SaleEntity.CustomFields." + fieldSaleIsLinkedToERP);
Bool saleIsLinkedToERP = false; 

//Check if this sale is already sent to ERP by looking at the user def field value.
if (!saleIsLinkedToERP_Value.isEmpty() && saleIsLinkedToERP_Value.after("[").until(":") == "I")
{
    if (!saleIsLinkedToERP_Value.after(":").until("]").isNumber())
    {
        saleIsLinkedToERP = true;
    }
    else if (saleIsLinkedToERP_Value.after(":").until("]").toInteger() > 0)
    {
        saleIsLinkedToERP = true;
    }
}
else if (!saleIsLinkedToERP_Value.isEmpty() && saleIsLinkedToERP_Value.getLength() > 0)
{
    saleIsLinkedToERP = true;
}
if (saleIsLinkedToERP)
{
    ed.setMessage("\r\nThe sale '" + saleName +"' is already sent to " + erpPlatform + ".\r\n\r\nThis order cannot be updated in " + erpPlatform + ".");
}
else
{
    //Check if this sale is set to sold, if that is the only state we allow to sent the sale to ERP (see configuration).
    if (saleStatus.isEmpty() || (saleStatus != "2" && allowOnlySaleWithStatusSold))
    {
        ed.setMessage("\r\nThe sale '" + saleName +"' is not marked as 'Sold'.\r\n\r\nMake sure the sale status is set to 'Sold' first.");
    }
    else
    {
        //Check if this sale has a quote and that it is set to 'Sold'.
        NSQuoteAgent quoteAgent;
        NSQuoteEntity quote = quoteAgent.GetQuoteEntityFromSaleId(saleId.toInteger());
        quoteId = quote.GetQuoteId();
        NSQuoteVersion[] quoteVersions = quoteAgent.GetQuoteVersions(quoteId);
        if (quoteVersions.length() > 0)
        {
            NSQuoteVersion quoteVersion = quoteVersions[0];
            quoteVersionState = quoteVersion.GetState();
        }

        if (quoteVersionState != 9)
        {
            ed.setMessage("\r\nThe quote for sale '" + saleName +"' is not marked as 'Sold'.\r\n\r\nMark the quote as 'Sold' by using the 'Place order' feature.");
        }
        else 
        {
            //Check if the company is already sent to ERP. 
            if (!contactId.isEmpty() && contactId.toInteger() > 0)
            {
                NSContactAgent contactAgent;
                NSContactEntity contact = contactAgent.GetContactEntity(contactId.toInteger());
                Map contactFields = contact.GetUserDefinedFields();
                contactIsLinkedToERP_Value = contactFields.get(fieldContactIsLinkedToERP);
            }
        
            if (!contactIsLinkedToERP_Value.isEmpty() && contactIsLinkedToERP_Value == "True")
            {
                contactIsLinkedToERP = true;
            }
        
            if (!contactIsLinkedToERP)
            {
                ed.setMessage("\r\nThe company '" + contactName +"' is not available in " + erpPlatform + ".\r\n\r\nCreate the company in " + erpPlatform + " first.");
            }
            else if (!contactId.isEmpty() && contactId.toInteger() > 0 && !contactName.isEmpty() && !personId.isEmpty() && personId.toInteger() > 0 && !personName.isEmpty()) 
            {
                //Check if the contact is already sent to ERP. We don't allow sales without a contact.
                NSPersonAgent personAgent;
                NSPersonEntity person = personAgent.GetPersonEntity(personId.toInteger());
                Map personFields = person.GetUserDefinedFields();
                personIsLinkedToERP_Value = personFields.get(fieldPersonIsLinkedToERP);
        
                if (!personIsLinkedToERP_Value.isEmpty() && personIsLinkedToERP_Value == "True")
                {
                    personIsLinkedToERP = true;
                }
        
                if (!personIsLinkedToERP)
                {
                    ed.setMessage("\r\nThe contact '" + personName +"' is not available in " + erpPlatform + ".\r\n\r\nCreate the contact in " + erpPlatform + " first.");
                }
                else 
                {
                    //Call the DataBridge instant job and wait for its response.
                    try {
                        HTTP h;
                        XMLNode root = parseJSON(String(h.get(instantJobUrl + "&QuoteId=" + quoteId.toString())));
                        String linesProcessed = root.getValueFromPath("LinesProcessed");
        
                        if (!linesProcessed.isEmpty() && linesProcessed.toInteger() >= 1)
                        {
                            ed.setMessage("\r\nThe order '" + saleName +"' is created.");
        
                            //Set the 'Is linked to ERP' field to 'True'
                            NSPersonAgent agent;
                            NSPersonEntity person = agent.GetPersonEntity(personId.toInteger());
                            Map fields;
                            fields.insert(fieldPersonIsLinkedToERP, "[I:1]");
                            person.SetUserDefinedFields(fields);
                            agent.SavePersonEntity(person);
                        }
                        else
                        {
                            ed.setMessage("\r\nThe order '" + saleName +"' could not be created.\r\n\r\nCheck the values in " + erpPlatform + ".");
                        }
        
                    }
                    catch {
                        ed.setMessage("Exception: \r\n" + error);
                    }
                }
            }
            else 
            {
                ed.setMessage("\r\nThe order does not have a contact linked.\r\n\r\nMake sure a company and contact are linked to the sale.");
            }
        }
    }
}

ed.setBlockExecution(true);

